package com.emmy.walnut.view;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.os.Bundle;

import com.emmy.walnut.R;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {

    private List<Fragment> fragments;
    private List<String> pageTitles;
    private FragmentPagerAdapter fragmentPagerAdapter;
    private ViewPager viewPager;
    private TabLayout mTabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        initPremission();
    }

    private void init(){
        fragments = new ArrayList<>();
        fragments.add(new ActivityFragment());
        fragments.add(new ClassFragment());
        fragments.add(new StatisticsFragment());
        fragments.add(new MyFragment());

        pageTitles = new ArrayList<>();
        pageTitles.add("活动");
        pageTitles.add("类别");
        pageTitles.add("统计");
        pageTitles.add("我的");

        fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return pageTitles.get(position);
            }
        };

        viewPager = (ViewPager)findViewById(R.id.main_layout);
        viewPager.setAdapter(fragmentPagerAdapter);

        mTabLayout = (TabLayout)findViewById(R.id.tabs);
        //将TabLayout和ViewPager关联起来
        mTabLayout.setupWithViewPager(viewPager);
    }

    /**
     * 动态申请权限
     */
    private void initPremission(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
